package ru.ifmo.thesis.event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class EventManager {
	
	private final Map<String, List<EventListener>> type2listener = new HashMap<String, List<EventListener>>();
	
	public void addEventListener(String eventName, EventListener listener) {
		List<EventListener> listeners = getListenersByName(eventName);
		if (listeners.contains(listeners)) {
			throw new IllegalStateException("Listener was already added for same event name");
		}
		listeners.add(listener);
	}

	public void removeEventListener(String eventName, EventListener listener) {
		for (Iterator<EventListener> it = getListenersByName(eventName).iterator(); 
				it.hasNext();) {
			
			if (it.next() == listener) {
				it.remove(); 
				return;
			}
		}
	}
	
	public void fireEvent(Event event) {
		for (EventListener l : getListenersByName(event.getEventName())) {
			l.fireEvent(event);
		}
	}
	
	private List<EventListener> getListenersByName(String eventName) {
		if (!type2listener.containsKey(eventName)) {
			type2listener.put(eventName, new ArrayList<EventListener>());
		}
		
		return type2listener.get(eventName);		
	}

}
